/*
 * @Description: 
 * @Author: Tang Weitian
 * @Date: 2021-09-29 10:41:28
 * @LastEditors: Tang Weitian
 * @LastEditTime: 2021-10-01 00:31:23
 */
import { Object3D, ShapeGeometry, MeshBasicMaterial, Mesh, FontLoader, PlaneGeometry, TextureLoader } from 'three';
import { TimelineLite, Back } from 'gsap';

export default class AnimatedPlane extends Object3D {
  constructor(img, { size = 0.8, width = 8, height = 7.6, color = '#000000', duration = 0.6, opacity = 1, wireframe = false } = {}) {
    super();

    this.size = size;

    const geom = new PlaneGeometry(width, height)
    const loader = new TextureLoader().load(img)
    const material = new MeshBasicMaterial({
      map: loader,
      opacity: 0,
      transparent: true
    })
    const plane = new Mesh(geom, material);
    this.add(plane)

    // Timeline
    this.tm = new TimelineLite({ paused: true });
    this.tm.set({}, {}, `+=${duration * 1.1}`)
    this.children.forEach((letter) => {
      const data = {
        opacity: 0,
        position: -0.5,
        wireframe
      };
      this.tm.to(data, duration, {
        opacity,
        position: 0,
        ease: Back.easeOut.config(2),
        onUpdate: () => {
          letter.material.opacity = data.opacity;
          letter.position.y = data.position;
          letter.position.z = data.position * 2;
          letter.rotation.x = data.position * 2;
        }
      }, `-=${duration - 0.03}`);
    });

    // Bind
    this.show = this.show.bind(this);
    this.hide = this.hide.bind(this);
  }

  show() {
    this.tm.play();
  }

  hide() {
    this.tm.reverse();
  }
}